from PyQt5.QtWidgets import QTableWidgetItem,QListWidget, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
from common import signalHandle
import json
from time import time
from datetime import datetime
from winsound import Beep
from info import instrumenID_dc
class TableData:
    def __init__(self,table,tqApi) -> None:
        with open('./db.json','r')as f:
            self.data=json.load(f)
        self.tableView,self.tqApi,self.signalHandle=table,tqApi,signalHandle
        
        self.KlinesDict={}
        self.RowColTable={}
        self.warnTimestamp={}
        self.getKlines()
        self.colHeaders=['latestP','minH','aveVol_Num','aveVol_Ration']
        self.rowNum,self.cloNum=len(self.data),len(self.colHeaders)
        [self.tableView.insertRow(0) for i in range(self.rowNum)]
        [self.tableView.insertColumn(0) for i in range(self.cloNum)]
        self.tableView.setHorizontalHeaderLabels(self.colHeaders)
        self.rowHeafers=[k for k in self.data]
        self.tableView.setVerticalHeaderLabels(self.rowHeafers)

        self.updateAll()
        self.tableView.cellChanged.connect(self.cellChanged)

        self.signalHandle.TQwaitUpdateSig.connect(self.dataUpdate)
    def cellChanged(self,row,col):
        colName=self.indexTostr(col)
        if colName in ['minH','aveVol_Num','aveVol_Ration']:
            columnName,rowName=self.indexTostr(col),self.indexTostr(row,isColIndex=False)
            self.data[rowName][columnName]=int(self.tableView.item(row,col).text())
            with open('./db.json','w')as f:
                json.dump(self.data,f)
            print('更新')
    def strToindex(self,Name,isColIndex=True):
        return self.colHeaders.index(Name) if isColIndex else self.rowHeafers.index(Name)
    def indexTostr(self,index,isColIndex=True):
        return  self.tableView.horizontalHeaderItem(index).text() if isColIndex else self.tableView.verticalHeaderItem(index).text()
    def updateAll(self):
        '''初始化界面'''
        
        for ID in self.data:
            self.warnTimestamp[ID]=0
            for colName in self.data[ID]:
                row=self.strToindex(ID,isColIndex=False)
                col=self.strToindex(colName,isColIndex=True)
                self.RowColTable[ID+colName]=(row,col)
                newItem=QTableWidgetItem(str(self.data[ID][colName]))
                newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)  
                self.tableView.setItem(row,col,newItem)
    def getKlines(self):
        for ID in self.data:

            subscribeStr=instrumenID_dc[ID]['exchange']+'.'+ID+instrumenID_dc[ID]['IDdate']
            kline=self.tqApi.api.get_kline_serial(subscribeStr, 60)
            self.KlinesDict[ID]=kline

    def dataUpdate(self):
        for ID,kline in self.KlinesDict.items():
            latestPrice=kline.close.iloc[-1]
            row,col=self.RowColTable[ID+'latestP']
            newItem=QTableWidgetItem(str(latestPrice))
            newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)  
            self.tableView.setItem(row,col,newItem)
            
            #20秒以内不重复预警
            if time()-self.warnTimestamp[ID]<30:continue
            #单根线高度预警

            if abs(latestPrice-kline.open.iloc[-1])/instrumenID_dc[ID]['miniPrice']>self.data[ID]['minH']:
                warnMsg='%s  1分钟高度超过 %d'%(ID,self.data[ID]['minH'])
                self.emitWarn(ID,warnMsg)
                return
            if abs(latestPrice-kline.open.iloc[-2])/instrumenID_dc[ID]['miniPrice']>self.data[ID]['minH']*1.5:
                warnMsg='%s  2分钟高度超过 %.f'%(ID,self.data[ID]['minH']*1.5)
                self.emitWarn(ID,warnMsg)
                return
                
            #成交量放大    不要猜发动  爆量预警取消
            # Nrows=kline.__len__()
            # AveVolume=kline.iloc[Nrows-self.data[ID]['aveVol_Num']-1:Nrows-1]['volume'].mean() 
            # if kline.volume.iloc[-1]>self.data[ID]['aveVol_Ration']*AveVolume:  
            #     warnMsg='%s  成交量放大'%(ID)
            #     self.emitWarn(ID,warnMsg)
            #     return
                
    def emitWarn(self,ID,warnMsg):
        Beep(200,200)
        self.warnTimestamp[ID]=time()
        time_string = datetime.fromtimestamp(time()).strftime('%H:%M:%S')
        warnDict={
            "ID":ID+instrumenID_dc[ID]['IDdate'],
            "timeStr":time_string,
            "warnMsg":warnMsg
        }
        self.signalHandle.warnMsgSignal.emit(warnDict)

# * id: 1234 (k线序列号)
# * datetime: 1501080715000000000 (K线起点时间(按北京时间)，自unix epoch(1970-01-01 00:00:00 GMT)以来的纳秒数)
# * open: 51450.0 (K线起始时刻的最新价)
# * high: 51450.0 (K线时间范围内的最高价)
# * low: 51450.0 (K线时间范围内的最低价)
# * close: 51450.0 (K线结束时刻的最新价)
# * volume: 11 (K线时间范围内的成交量)
# * open_oi: 27354 (K线起始时刻的持仓量)
# * close_oi: 27355 (K线结束时刻的持仓量)